package com.xxh.securitydemo.compoent;


import cn.hutool.core.lang.Dict;
import com.alibaba.fastjson.JSON;
import com.xxh.securitydemo.dao.UmsAdminDao;
import com.xxh.securitydemo.model.UmsAdmin;
import com.xxh.securitydemo.service.AdminService;
import com.xxh.securitydemo.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//登录认证成功处理事件
@Component
public class CuLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    JWTUtils jwtUtils;

    @Autowired
    AdminService adminService;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

        //取得用户信息
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //生成token
        String token = jwtUtils.generateToken(userDetails);

        //详细信息
        UmsAdmin admin = adminService.getAdminByUsername(userDetails.getUsername());
        httpServletResponse.setContentType("text/json;charset=utf-8");
        Dict set = Dict.create()
                .set("code", "200")
                .set("msg","successLogin")
                .set("token",token)
                .set("username",admin.getUsername()).set("avatar",admin.getIcon());
        httpServletResponse.getWriter().write(JSON.toJSONString(set));
    }
}
